package cayte.xiami.in.ui;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.FrameLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import cayte.xiami.in.AccountInfo;
import cayte.xiami.in.CheckinHandler;
import cayte.xiami.in.D;
import cayte.xiami.in.R;
import cayte.xiami.in.ad.AdUtil;
import cayte.xiami.in.helper.Check;
import cayte.xiami.in.helper.DBHelper;
import cayte.xiami.in.helper.PaperHelper;
import cayte.xiami.in.helper.SpfHelper;
import cayte.xiami.in.ui.CheckinAsyncTask.CheckinCallBack;

import com.cayte.layout.CayteLayoutHelper;
import com.cayte.layout.CayteLayoutHelper.OnLayoutTransparent;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.NotificationType;
import com.umeng.fb.UMFeedbackService;
import com.umeng.update.UmengUpdateAgent;

public class CheckinActivity extends Activity {

	private View top, tran, backUser, backSetting;
	public CayteLayoutHelper layoutHelper;
	private FrameLayout progressLayout;
	private TextView dayText, dayTip;
	private ScrollView dayDetailScroll;
	private TextView dayDetail;
	private AccountListView accListView;
	private SettingView setView;

	private CheckinAsyncTask checkinTask = null;
	public SpfHelper spfHelper = null;
	private ProgressView progress = null;

	public DBHelper dataBase = null;

	private final Handler handler = new Handler();

	public static final String ACTION_TIP_RECEIVER = "cayte.xiami.in.receiver.tip";
	private TipReceiver tipReceiver = null;

	private class TipReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(ACTION_TIP_RECEIVER)) {
				initUI();
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		MobclickAgent.updateOnlineConfig(this);

		tipReceiver = new TipReceiver();
		spfHelper = new SpfHelper(this);
		dataBase = new DBHelper(this);
		progress = new ProgressView(this, R.color.transparent, R.color.white);

		top = findViewById(R.id.layoutTop);
		tran = findViewById(R.id.layoutTransparent);
		backUser = findViewById(R.id.layoutBackUser);
		backSetting = findViewById(R.id.layoutBackSetting);
		layoutHelper = new CayteLayoutHelper(this, top,
				CayteLayoutHelper.HORIZONTAL);
		layoutHelper.setLeftBackView(backSetting);
		layoutHelper.setRightBackView(backUser);
		layoutHelper.setOnLayoutTransparent(new OnLayoutTransparent() {

			@Override
			public void update(int current, int orientation) {
				// TODO Auto-generated method stub
				float total = layoutHelper.SCREEN_WIDTH - layoutHelper.MARGIN;
				float percentage = Math.abs(current) / total;
				int alpha = (int) (percentage * 160);
				tran.setBackgroundColor(Color.argb(alpha, 0, 0, 0));
			}
		});

		top.setOnTouchListener(layoutHelper.getOnLayoutTouchListener());

		accListView = new AccountListView(this);
		setView = new SettingView(this);

		progressLayout = (FrameLayout) findViewById(R.id.progressLayout);
		dayText = (TextView) findViewById(R.id.dayText);
		dayTip = (TextView) findViewById(R.id.dayTip);
		dayDetailScroll = (ScrollView) findViewById(R.id.dayDetailScroll);
		dayDetail = (TextView) findViewById(R.id.dayDetail);

		setTextStyle();

		setBoldTextView(dayText);

		dayText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (isCheckinTaskRun())
					return;
				AccountInfo[] arr = dataBase.queryArray();
				if (arr.length > 0)
					doChecinTask(arr);
				else {
					D.show(CheckinActivity.this, R.string.noAccountTip);
					layoutHelper.OpenToRight();
				}
			}
		});

		// Umeng Update
		UmengUpdate();
		//
		AdUtil.create(this);

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		checkShowTipDialog();
	}

	private void checkShowTipDialog() {
		String tipDialog = MobclickAgent.getConfigParams(this, "tip_dialog");
		if (!tipDialog.equals(Check.OFF)) {
			String[] tipVers = tipDialog.split(",");
			boolean isShow = false;
			String current = null;
			try {
				PackageManager pm = getPackageManager();
				PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
				current = pi.versionName;
			} catch (Exception e) {
			}
			if (current != null)
				for (String ver : tipVers) {
					if (ver != null && !ver.equals("") && ver.equals(current)) {
						isShow = true;
						break;
					}
				}
			if (isShow) {
				String content = MobclickAgent.getConfigParams(this,
						"tip_dialog_content");
				showTipDialog(content);
			}
		}
	}

	private void showTipDialog(String content) {
		new AlertDialog.Builder(this).setMessage(content)
				.setPositiveButton(R.string.know, null).setCancelable(false)
				.create().show();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter intentFilter = new IntentFilter(ACTION_TIP_RECEIVER);
		registerReceiver(tipReceiver, intentFilter);
		MobclickAgent.onResume(this);
		initUI();
		// layoutHelper.invalidate();
		post2LayoutState(layoutHelper.getState(), 200);
		accListView.initData();
		setView.initData();

		// change background
		boolean isUseWallpaper = spfHelper.isUseWallpaper();
		Drawable draw = null;
		try {
			if (isUseWallpaper)
				draw = new BitmapDrawable(PaperHelper.handlerWallpaper(this,
						getWallpaper()));
		} catch (Exception e) {
			// TODO: handle exception
			spfHelper.setUseWallpaper(false);
			isUseWallpaper = spfHelper.isUseWallpaper();
		}
		if (!isUseWallpaper)
			draw = new BitmapDrawable(PaperHelper.getPaper(this));

		top.setBackgroundDrawable(draw);

		// change day detail
		if (spfHelper.isShowDetailLog()) {
			dayDetailScroll.setVisibility(View.VISIBLE);
		} else {
			dayDetail.setText("");
			dayDetailScroll.setVisibility(View.GONE);
		}

		dayDetailScroll.setOnTouchListener(startPanelListener);

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPause(this);
		unregisterReceiver(tipReceiver);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		layoutHelper.To(CayteLayoutHelper.NORMAL);
		timer.cancel();
		timer.purge();
	}

	public void initUI() {
		// TODO Auto-generated method stub
		String lastCheckString = "";
		ArrayList<AccountInfo> accs = dataBase.query();
		if (accs != null && accs.size() == 0) {
			lastCheckString = "";
		} else if (accs != null && accs.size() == 1) {
			if (accs.get(0).day > 0)
				lastCheckString = String.format(
						getString(R.string.simpleDetail), accs.get(0).day);
			else
				lastCheckString = "";
		} else {
			lastCheckString = spfHelper.getLastCheckString();
		}
		accs = null;
		if (spfHelper.checkLastCheckDate()) {
			dayText.setText(R.string.everydayCheckin);
			if (D.isNull(spfHelper.getLastCheckString()))
				dayTip.setText("");
			else
				dayTip.setText(String.format(getString(R.string.itemLast),
						spfHelper.getLastCheckString()));
		} else {
			dayText.setText(R.string.checkined);
			dayTip.setText(lastCheckString);
		}
	}

	private boolean isCheckinTaskRun() {
		// TODO Auto-generated method stub
		if (checkinTask == null)
			return false;
		return checkinTask.isRun;
	}

	private void cancelChecinTask() {
		// TODO Auto-generated method stub
		if (checkinTask != null)
			checkinTask.cancel();
		checkinTask = null;
	}

	private void doChecinTask(AccountInfo[] arr) {
		// TODO Auto-generated method stub
		cancelChecinTask();
		checkinTask = new CheckinAsyncTask(getApplicationContext(),
				new CheckinCallBack() {
					@Override
					public void CheckinStart() {
						
						AdUtil.showPlaque(CheckinActivity.this);
						progress.show(progressLayout, 10f);
					}

					@Override
					public void CheckinOne(AccountInfo acc) {
						// TODO Auto-generated method stub
						if (acc.state == CheckinHandler.SUCCESS
								|| acc.state == CheckinHandler.IS_CHECKED) {
							dataBase.updataOne(acc);
						}
					}

					@Override
					public void CheckinEnd(ArrayList<AccountInfo> accs) {
						// TODO Auto-generated method stub
						D.e("CheckinActivity : CheckinEnd");
						boolean success = true;
						StringBuffer sb = new StringBuffer();
						for (AccountInfo acc : accs) {
							if (acc.state != CheckinHandler.SUCCESS
									&& acc.state != CheckinHandler.IS_CHECKED) {
								if (D.isNull(sb))
									sb.append(CheckinActivity.this
											.getString(R.string.checkFail));
								sb.append("\n" + "-------------------");
								sb.append("\n" + acc.name);
								sb.append("\n" + acc.tip);
							}
						}
						success = D.isNull(sb);
						D.e("CheckinActivity : CheckinEnd , success is "
								+ success);
						if (success) {
							spfHelper.saveLastCheck();
							dayText.setText(R.string.checkined);
							if (accs.size() == 1)
								dayTip.setText(String.format(
										getString(R.string.simpleDetail),
										accs.get(0).day));
							else
								dayTip.setText(spfHelper.getLastCheckString());

							accListView.initData();
						} else {
							// Toast.makeText(CheckinActivity.this, sb,
							// Toast.LENGTH_LONG).show();
							if (!spfHelper.checkLastCheckDate()) {
								dayText.setText(R.string.checkined);
								if (accs.size() == 1)
									dayTip.setText(String.format(
											getString(R.string.simpleDetail),
											accs.get(0).day));
								else
									dayTip.setText(spfHelper
											.getLastCheckString());
							} else {
								dayText.setText(R.string.everydayCheckin);
								dayTip.setText(R.string.tCheckFail);
							}
						}

						progress.dismiss(progressLayout);
						fadeOutDayDetail();
					}

					@Override
					public void CheckinLog(String log) {
						// TODO Auto-generated method stub
						appendDayDetailText(log);
					}
				});
		checkinTask.execute(arr);
	}

	private void setBoldTextView(TextView tv) {
		tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
		tv.getPaint().setFakeBoldText(true);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		cancelChecinTask();
		//
		AdUtil.destory(this);
		super.onDestroy();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
		}
	}

	private void UmengUpdate() {
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.setUpdateAutoPopup(true);
		UmengUpdateAgent.setUpdateListener(null);
		UmengUpdateAgent.update(this);

		UMFeedbackService.enableNewReplyNotification(this,
				NotificationType.NotificationBar);
	}

	private String dayDetailText = "";

	Runnable dayDetailTextRunnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			dayDetail.setText(dayDetailText);
			dayDetailScroll.scrollBy(0, dayDetail.getMeasuredHeight());
		}
	};

	private void appendDayDetailText(String dayDetailText) {
		// TODO Auto-generated method stub
		this.dayDetailText += dayDetailText + "\n";
		handler.post(dayDetailTextRunnable);
	}

	private void fadeOutDayDetail() {
		// TODO Auto-generated method stub
		startPanelTimer();
	}

	private boolean isDoPanelAnim = false;
	private Timer timer = new Timer(true);

	private boolean isPanelShow() {
		// TODO Auto-generated method stub
		return !dayDetail.getText().equals("");
	}

	private void startPanelTimer() {
		// TODO Auto-generated method stub
		timer.cancel();
		timer.purge();
		timer = new Timer(true);
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						hidePanel();
					}
				});
			}
		}, 5000);
	}

	private void hidePanel() {
		// TODO Auto-generated method stub
		if (!isPanelShow())
			return;
		if (isDoPanelAnim)
			return;
		isDoPanelAnim = true;
		dayDetailScroll.clearAnimation();
		Animation anim = new AlphaAnimation(1f, 0f);
		anim.setDuration(500);
		anim.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				// TODO Auto-generated method stub
				dayDetailText = "";
				dayDetail.setText("");
				isDoPanelAnim = false;
			}
		});
		dayDetailScroll.startAnimation(anim);
	}

	private OnTouchListener startPanelListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				timer.cancel();
				timer.purge();
				break;
			case MotionEvent.ACTION_UP:
				startPanelTimer();
				break;
			default:
				break;
			}
			return false;
		}
	};

	final Runnable run2right = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			layoutHelper.To(CayteLayoutHelper.RIGHT);
		}
	};

	final Runnable run2left = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			layoutHelper.To(CayteLayoutHelper.LEFT);
		}
	};

	final Runnable run2normal = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			layoutHelper.To(CayteLayoutHelper.NORMAL);
		}
	};

	public void post2LayoutState(int state, long delay) {
		// TODO Auto-generated method stub
		switch (state) {
		case CayteLayoutHelper.LEFT:
			handler.postDelayed(run2left, delay);
			break;
		case CayteLayoutHelper.RIGHT:
			handler.postDelayed(run2right, delay);
			break;
		default:
			handler.postDelayed(run2normal, delay);
			break;
		}
	}

	private void setTextStyle() {
		// TODO Auto-generated method stub
		dayText.setShadowLayer(10, 2, 2, Color.GRAY);
		dayTip.setShadowLayer(10, 2, 2, Color.GRAY);
		dayDetail.setShadowLayer(10, 2, 2, Color.GRAY);

		dayText.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					dayText.setShadowLayer(35, 0, 0, Color.GRAY);
					break;
				case MotionEvent.ACTION_UP:
					dayText.setShadowLayer(10, 2, 2, Color.GRAY);
					break;
				default:
					break;
				}
				return false;
			}
		});
	}

}